<template>
    <div class="dashboard-container">
      <Add v-if="data.addShow" openKey="addShow" @setMData="setMData"></Add>
      <Adjust ref="adjustRef" @setMData="setMData"></Adjust>
      
      <div class="project-container">
      <div class="card-header">
        <span>项目列表</span>
      </div>

      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="项目名称">
          <el-input v-model="searchForm.name" placeholder="请输入项目名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="项目标识号">
          <el-input v-model="searchForm.uniqueId" placeholder="请输入项目标识号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div class="action-buttons">
        <el-button type="primary" @click="openAddDialog">增加项目</el-button>
        <el-button type="danger" @click="handleDelete" :disabled="!selectedProjects.length">批量删除</el-button>
      </div>
      
      <el-table 
        v-loading="loading"
        :data="projectList.slice((currentPage - 1) * pageSize, currentPage * pageSize)" 
        border 
        style="width: 100%; height: calc(100% - 120px)"
        element-loading-text="加载中..."
        element-loading-spinner="el-icon-loading"
        @selection-change="handleSelectionChange"
        :row-key="row => row.id"
        ref="projectTable"
        highlight-current-row
      >
        <el-table-column 
          type="selection" 
          width="55"
          :reserve-selection="true"
          align="center"
        ></el-table-column>
        <el-table-column prop="id" label="项目ID" width="100"></el-table-column>
        <el-table-column prop="name" label="项目名称" width="240"></el-table-column>
        <el-table-column prop="uniqueId" label="项目标识号" width="200"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="200"></el-table-column>
        <el-table-column prop="fileCount" label="文件数量" width="120"></el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleAdjust(scope.row)"
            >
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleSingleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        background
        layout="prev, pager, next"
        :total="projectList.length"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script setup>
// 项目列表页面 - 主要功能：项目展示、搜索、增删改查
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProjectList } from '@/api/project'
import Add from './Add.vue' // 项目添加组件
import Adjust from './Adjust.vue' // 项目修改组件
import { mockProjectList } from '@/api/mock/projectMock' // 开发环境mock数据

const instance = getCurrentInstance()
const route = useRoute()
const router = useRouter()

// 添加分页相关变量和方法
const currentPage = ref(1)
const pageSize = ref(10)

/**
 * 处理分页变化
 * @param {number} val - 新的页码
 */
const handleCurrentChange = (val) => {
  currentPage.value = val
}

const data = reactive({
  addShow: false,
})
const adjustRef = ref(null)
const projectList = ref([])
const selectedProjects = ref([])
const searchForm = reactive({
  name: '',
  uniqueId: ''
})
const loading = ref(false)

/**
 * 处理子组件传递的数据变更事件
 * @param {string} type - 数据类型标识
 * @param {any} value - 新值
 */
function setMData(type, value) {
  console.log('收到setMData事件:', type, value)
  if (type === 'refreshList') {
    console.log('开始刷新项目列表...')
    loading.value = true  // 添加加载状态
    fetchProjectList().then(() => {
      console.log('项目列表刷新完成', projectList.value)
      loading.value = false
      //ElMessage.success('列表已刷新')  // 添加成功提示
    }).catch(error => {
      console.error('刷新列表失败:', error)
      loading.value = false
      //ElMessage.error('刷新列表失败')
    })
  } else {
    data[type] = value;
  }
}


/**
 * 获取项目列表数据
 * 开发环境使用mock数据，生产环境调用API
 */
const fetchProjectList = async () => {
  loading.value = true  // 添加加载状态
  try {
    if (import.meta.env.DEV) {
      // 开发环境下强制重新获取mock数据
      const { mockProjectList } = await import('@/api/mock/projectMock')
      projectList.value = mockProjectList
    } else {
      const res = await getProjectList()
      if (route.query.projKey) {
        projectList.value = res.data.filter(project => project.uniqueId === route.query.projKey)
      } else {
        projectList.value = res.data
      }
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    throw error  // 抛出错误以便上层捕获
    } finally {
      loading.value = false
    }
}

/**
 * 处理项目搜索
 * 根据项目名称或标识号进行筛选
 */
const handleSearch = async () => {
  if (!searchForm.name && !searchForm.uniqueId) {
    fetchProjectList()
    return
  }
    loading.value = true
    try {
      if (import.meta.env.DEV) {
        // 开发环境使用mock数据
        projectList.value = mockProjectList.filter(p => 
          (searchForm.name && p.name.includes(searchForm.name.trim())) || 
          (searchForm.uniqueId && p.uniqueId.includes(searchForm.uniqueId.trim())))
      } else {
        // 生产环境使用真实API
        const res = await getProjectList()
        projectList.value = res.data.filter(p => 
          (searchForm.name && p.name.includes(searchForm.name.trim())) || 
          (searchForm.uniqueId && p.uniqueId.includes(searchForm.uniqueId.trim())))
      }
    } catch (error) {
      console.error('搜索项目失败:', error)
      if (import.meta.env.DEV) {
        // 开发环境错误处理
        projectList.value = mockProjectList
      }
    } finally {
      loading.value = false
      // 只在有搜索条件时显示提示
      if (searchForm.name || searchForm.uniqueId) {
        if (projectList.value.length > 0) {
          ElMessage.success(`找到${projectList.value.length}个项目`)
        } else {
          ElMessage.warning('没有找到匹配的项目')
        }
      }
    }
}

/**
 * 打开添加项目对话框
 */
const openAddDialog = () => {
  data.addShow = true
}

/**
 * 重置搜索表单并刷新列表
 */
const handleReset = () => {
  searchForm.name = ''
  searchForm.uniqueId = ''
  fetchProjectList()
}

/**
 * 处理表格行选择变化
 * @param {array} selection - 选中的行数据数组
 */
const handleSelectionChange = (selection) => {
  console.log('Selected projects:', selection)
  console.log('Current projectList:', projectList.value)
  selectedProjects.value = selection
}

/**
 * 处理修改项目操作
 * @param {object} row - 要修改的项目数据
 */
const handleAdjust = (row) => {
  console.log('点击修改按钮，项目数据:', row)
  if (!adjustRef.value) {
    console.error('Adjust组件未初始化')
    return
  }
  adjustRef.value.handleOpen(row)
}

/**
 * 处理单个项目删除
 * @param {object} row - 要删除的项目数据
 */
const handleSingleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除项目"${row.name}"吗?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (import.meta.env.DEV) {
      const { mockDeleteProject } = await import('@/api/mock/projectMock')
      const res = await mockDeleteProject(row.id)
      if (res.data) {
        projectList.value = res.list
        ElMessage.success('删除成功')
      } else {
        throw new Error('删除失败')
      }
    } else {
      const { deleteProject } = await import('@/api/project')
      await deleteProject(row.id)
      ElMessage.success('删除成功')
      await fetchProjectList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }
}

/**
 * 处理批量删除操作
 * 删除所有选中的项目
 */
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量删除选中的${selectedProjects.value.length}个项目吗?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (import.meta.env.DEV) {
      // 开发环境使用mock数据
      const { mockDeleteProject } = await import('@/api/mock/projectMock')
      for (const project of selectedProjects.value) {
        console.log('正在删除项目:', project.id)
        const res = await mockDeleteProject(project.id)
        if (res.data) {
          console.log('删除成功:', project.id)
          projectList.value = res.list
        } else {
          console.error('删除失败:', project.id)
          throw new Error(`删除项目${project.id}失败`)
        }
      }
      ElMessage.success('删除成功')
    } else {
      // 生产环境逐个调用删除接口
      const { deleteProject } = await import('@/api/project')
      for (const project of selectedProjects.value) {
        console.log('正在删除项目:', project.id)
        try {
          await deleteProject(project.id)
          console.log('删除成功:', project.id)
        } catch (err) {
          console.error('删除失败:', err)
          throw new Error(`删除项目${project.id}失败: ${err.message}`)
        }
      }
      ElMessage.success('删除成功')
      await fetchProjectList()
    }
    selectedProjects.value = []
  } catch (error) {
    console.error('删除操作出错:', error)
    if (error !== 'cancel') {
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }
}

// 组件挂载时获取项目列表
onMounted(() => {
  fetchProjectList()
})

</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-width: 1200px;
}

.project-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  min-width: 1200px;
  overflow-x: auto;
}
.card-header {
  font-size: 18px;
  font-weight: bold;
  min-width: 1200px;
}
.search-form {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}
</style>
